#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
View Specifications 按钮验证脚本 - 自动化版本
带界面但自动关闭
"""

import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.action_chains import ActionChains

class AutoViewSpecVerifier:
    """自动化 View Specifications 验证器"""
    
    def __init__(self):
        self.setup_driver()
        
    def setup_driver(self):
        """设置Chrome WebDriver"""
        chrome_options = Options()
        chrome_options.add_argument('--disable-blink-features=AutomationControlled')
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_argument('--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15')
        
        service = Service(ChromeDriverManager().install())
        self.driver = webdriver.Chrome(service=service, options=chrome_options)
        self.wait = WebDriverWait(self.driver, 15)
        self.actions = ActionChains(self.driver)
    
    def verify_buttons_auto(self):
        """自动验证按钮（30秒后自动关闭）"""
        try:
            print("🔍 开始自动验证 View Specifications 按钮")
            print("⏰ 验证将在30秒后自动结束")
            
            # 访问页面
            url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-DH&planId=c"
            print(f"📖 访问页面...")
            self.driver.get(url)
            time.sleep(8)
            
            # 处理Cookie
            self.handle_cookies()
            time.sleep(3)
            
            # 等待车型元素加载
            print(f"⏳ 等待车型元素加载...")
            try:
                self.wait.until(lambda d: len(d.find_elements(By.CSS_SELECTOR, 'div[data-cy]')) > 0)
                print(f"✓ 检测到页面元素")
            except:
                print(f"⚠️  页面元素加载超时，继续验证...")
            
            # 获取所有车型
            car_elements = self.driver.find_elements(By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]')
            if not car_elements:
                # 备用选择器
                car_elements = self.driver.find_elements(By.CSS_SELECTOR, 'div[data-cy]')
                filtered_elements = []
                for el in car_elements:
                    class_attr = el.get_attribute('class')
                    if class_attr and 'ProductTile' in class_attr:
                        filtered_elements.append(el)
                car_elements = filtered_elements
            
            print(f"🚗 找到 {len(car_elements)} 个车型元素")
            
            if len(car_elements) == 0:
                print(f"❌ 未找到车型元素，尝试调试...")
                self.debug_page_content()
                return {}
            
            results = {}
            
            for i, car_element in enumerate(car_elements):
                car_name = car_element.get_attribute('data-cy')
                if not car_name:
                    continue
                    
                print(f"\n🔍 [{i+1}/{len(car_elements)}] 检查车型: {car_name}")
                
                # 检查可见性
                is_displayed = car_element.is_displayed()
                is_in_viewport = self.is_in_viewport(car_element)
                print(f"   可见性: displayed={is_displayed}, in_viewport={is_in_viewport}")
                
                button_results = {}
                
                if is_displayed:
                    # 滚动到元素并悬停
                    self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", car_element)
                    time.sleep(1)
                    self.actions.move_to_element(car_element).perform()
                    time.sleep(2)
                    
                    # 尝试不同的选择器
                    selectors_to_test = [
                        ('data-cy="product-tile-overlay"', 'button[data-cy="product-tile-overlay"]'),
                        ('ButtonAsLink类', 'button[class*="ButtonAsLink"]'),
                        ('kMrUGm类', 'button.kMrUGm'),
                        ('aria-hidden=false', 'button[aria-hidden="false"]'),
                        ('所有button', 'button')
                    ]
                    
                    for desc, selector in selectors_to_test:
                        try:
                            if selector == 'button':
                                # 特殊处理：查找所有按钮并检查文本
                                buttons = car_element.find_elements(By.CSS_SELECTOR, selector)
                                matching_buttons = []
                                for btn in buttons:
                                    text = btn.text.strip()
                                    data_cy = btn.get_attribute('data-cy')
                                    class_attr = btn.get_attribute('class')
                                    
                                    if ('View Specifications' in text or 
                                        data_cy == 'product-tile-overlay' or
                                        (class_attr and 'ButtonAsLink' in class_attr)):
                                        matching_buttons.append({
                                            'text': text,
                                            'data_cy': data_cy,
                                            'class': class_attr,
                                            'visible': btn.is_displayed()
                                        })
                                
                                if matching_buttons:
                                    print(f"   ✓ {desc}: 找到 {len(matching_buttons)} 个匹配按钮")
                                    for btn_info in matching_buttons:
                                        print(f"      - 文本: '{btn_info['text']}'")
                                        print(f"      - data-cy: '{btn_info['data_cy']}'")
                                        print(f"      - 可见: {btn_info['visible']}")
                                    button_results[desc] = matching_buttons
                                else:
                                    print(f"   ❌ {desc}: 无匹配按钮")
                            else:
                                # 普通CSS选择器
                                buttons = car_element.find_elements(By.CSS_SELECTOR, selector)
                                visible_buttons = [btn for btn in buttons if btn.is_displayed()]
                                
                                if visible_buttons:
                                    print(f"   ✓ {desc}: 找到 {len(visible_buttons)} 个可见按钮")
                                    btn_info = []
                                    for btn in visible_buttons:
                                        info = {
                                            'text': btn.text.strip(),
                                            'data_cy': btn.get_attribute('data-cy'),
                                            'class': btn.get_attribute('class')
                                        }
                                        btn_info.append(info)
                                        print(f"      - 文本: '{info['text']}', data-cy: '{info['data_cy']}'")
                                    button_results[desc] = btn_info
                                else:
                                    print(f"   ❌ {desc}: 无可见按钮")
                                    
                        except Exception as e:
                            print(f"   ❌ {desc}: 出错 - {e}")
                
                results[car_name] = {
                    'visible': is_displayed,
                    'in_viewport': is_in_viewport,
                    'button_results': button_results,
                    'has_any_button': len(button_results) > 0
                }
            
            # 输出总结
            self.print_results_summary(results)
            
            # 保存结果
            with open('auto_view_spec_verification.json', 'w', encoding='utf-8') as f:
                json.dump(results, f, indent=2, ensure_ascii=False)
            print(f"\n💾 详细结果已保存到 auto_view_spec_verification.json")
            
            return results
            
        except Exception as e:
            print(f"❌ 验证过程出错: {e}")
            return {}
        finally:
            # 30秒后自动关闭
            print(f"\n⏰ 5秒后自动关闭浏览器...")
            time.sleep(5)
            self.driver.quit()
    
    def is_in_viewport(self, element):
        """检查元素是否在视口中"""
        try:
            return self.driver.execute_script("""
                var element = arguments[0];
                var rect = element.getBoundingClientRect();
                return (
                    rect.top >= 0 &&
                    rect.left >= 0 &&
                    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
                    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
                );
            """, element)
        except:
            return False
    
    def debug_page_content(self):
        """调试页面内容"""
        try:
            print(f"\n🔍 页面调试信息:")
            
            # 检查页面标题
            title = self.driver.title
            print(f"   页面标题: {title}")
            
            # 检查所有data-cy元素
            all_data_cy = self.driver.find_elements(By.CSS_SELECTOR, '[data-cy]')
            print(f"   所有data-cy元素: {len(all_data_cy)} 个")
            
            if all_data_cy:
                print(f"   前10个data-cy值:")
                for i, el in enumerate(all_data_cy[:10]):
                    data_cy = el.get_attribute('data-cy')
                    tag_name = el.tag_name
                    print(f"     {i+1}. {tag_name}[data-cy='{data_cy}']")
            
            # 检查所有包含"ProductTile"的元素
            product_tiles = self.driver.find_elements(By.CSS_SELECTOR, '[class*="ProductTile"]')
            print(f"   ProductTile类元素: {len(product_tiles)} 个")
            
        except Exception as e:
            print(f"   调试出错: {e}")
    
    def handle_cookies(self):
        """处理Cookie"""
        try:
            self.driver.execute_script("""
                var cookieElements = document.querySelectorAll('[class*="cookie"], [class*="Cookie"], [class*="consent"]');
                cookieElements.forEach(function(el) {
                    el.style.display = 'none';
                });
            """)
            print(f"✓ Cookie处理完成")
        except Exception as e:
            print(f"❌ Cookie处理出错: {e}")
    
    def print_results_summary(self, results):
        """打印结果总结"""
        try:
            print(f"\n📊 View Specifications 按钮验证总结:")
            print(f"="*60)
            
            total_cars = len(results)
            visible_cars = len([r for r in results.values() if r['visible']])
            cars_with_buttons = len([r for r in results.values() if r['has_any_button']])
            
            print(f"总车型数: {total_cars}")
            print(f"可见车型: {visible_cars}")
            print(f"有按钮的车型: {cars_with_buttons}")
            print(f"按钮发现率: {cars_with_buttons}/{visible_cars} = {cars_with_buttons/visible_cars*100:.1f}%" if visible_cars > 0 else "按钮发现率: 0%")
            
            print(f"\n📝 每个车型的详细结果:")
            for car_name, result in results.items():
                status = "✅" if result['has_any_button'] else "❌"
                visibility = "可见" if result['visible'] else "隐藏"
                print(f"  {status} {car_name}: {visibility}")
                
                if result['has_any_button']:
                    for method, buttons in result['button_results'].items():
                        if buttons:
                            print(f"      - {method}: 找到 {len(buttons)} 个按钮")
            
            # 分析最佳选择器
            if cars_with_buttons > 0:
                print(f"\n🎯 最佳选择器分析:")
                method_counts = {}
                for result in results.values():
                    if result['has_any_button']:
                        for method in result['button_results'].keys():
                            method_counts[method] = method_counts.get(method, 0) + 1
                
                sorted_methods = sorted(method_counts.items(), key=lambda x: x[1], reverse=True)
                for method, count in sorted_methods:
                    print(f"   {method}: {count}/{visible_cars} 车型成功")
            
        except Exception as e:
            print(f"❌ 总结输出出错: {e}")

def main():
    """主函数"""
    verifier = AutoViewSpecVerifier()
    results = verifier.verify_buttons_auto()
    
    if results:
        cars_with_buttons = len([r for r in results.values() if r['has_any_button']])
        visible_cars = len([r for r in results.values() if r['visible']])
        
        print(f"\n🏁 自动验证完成！")
        if cars_with_buttons == visible_cars and visible_cars > 0:
            print(f"🎉 所有可见车型都找到了 View Specifications 按钮！")
        elif cars_with_buttons > 0:
            print(f"⚠️  部分车型找到了按钮 ({cars_with_buttons}/{visible_cars})，需要优化选择器")
        else:
            print(f"❌ 没有找到任何 View Specifications 按钮，需要重新分析")

if __name__ == "__main__":
    main()
